﻿var richTextIsChange = false;
var timeTooltipInvisible = 2000;
var timerTooltipID;
var tooltipIsVisible = false;

$(function () {
    breaking();

    $("#richTextBox").mouseenter(function () {
        if (richTextIsChange) {
            breaking();
        }
    }).keyup(function () {
        richTextIsChange = true;
    }).blur(function () {
        if (richTextIsChange) {
            breaking();
        }
    });
    //bound event tooltip
    $("#tooltip").mouseover(function () {
        clearTimeout(timerTooltipID);
    }).mouseleave(function () {
        timerTooltipID = setTimeout("closeTooltip();", timeTooltipInvisible);
    });

    $(".toolbar-close").click(function () { closeTooltip(); })

})
function breaking() {
    var richTextBox = document.getElementById("richTextBox");
    var nodes = getTextNodesIn(richTextBox);
    for (var i = 0; i < nodes.length; i++) {
        var text = $(nodes[i]).text();
        if (text != "") {
            if (nodes[i].parentNode.tagName == "SPAN") {
                $(nodes[i].parentNode).replaceWith(breakingWords(text));
            }
            else {
                text = text.replace(/^\n*\s*/, "");
                if (text != "") {
                    $(nodes[i]).replaceWith(breakingWords(text));
                }
            }
        }
    }

    $(".tooltip-word").mouseover(function () {
        var isFound = loadDefinitionOfTerm(this);
        if (isFound) {
            showTooltip(this);
            clearTimeout(timerTooltipID);
            timerTooltipID = setTimeout("closeTooltip();", timeTooltipInvisible);
            tooltipIsVisible = true;
        }
    });
    richTextIsChange = false;
}

///load definition of term
///return true if the definition has found. otherwise false
function loadDefinitionOfTerm(term) {
    var text = $(term).text().toLowerCase();
    //remove redundacy characters at the begin
    text = text.replace(/^\.|,|\?|>|<|"|'|;|:|\(/, "");
    //remove redundacy characters at the end
    text = text.replace(/\.|,|\?|>|<|"|'|;|:|\)$/, "");
    //searching in you DB by using ajax and get json response 
    //in this case i use db in client machine. i store it at the end of the file

    var isFound = false;
    //loop
    for (var i = 0; i < arrDefinitionOfTerms.length; i++) {
        var def = arrDefinitionOfTerms[i];
        if (def.term == text) {            
            $("#tooltipHeader").text(text);
            $("#tooltipDefinition").text(def.definition);
            $("#tooltipLink").attr('href', def.url).text(def.url);
            isFound = true;
            break;
        }
    }
    return isFound;
}

function showTooltip(term) {
    var offset = $(term).offset();
    var tooltip = $("#tooltip");
    var windowWidth = getWindowWidth();
    var windowHeight = getWindowHeight();
    var tooltipWidth = tooltip.width();
    var tooltipHeight = tooltip.height();
    var x, y;
    //check width screen is still available for display
    var margin = 20;
    if (offset.left + tooltipWidth < windowWidth) {
        x = offset.left;
    }
    else {
        x = offset.left - tooltipWidth;
    }

    if (offset.top + tooltipHeight + margin < windowHeight) {
        y = offset.top + margin;
    }
    else {
        y = offset.top - tooltipHeight - margin;
    }

    tooltip.css({ left: x + "px", top: y + "px" }).fadeIn();
}

function breakingWords(text) {
    if (text.length == 1) {
        return "<span>" + text + "</span>";
    }
    else {
        text = text.replace(/&nbsp;/, " ");
        var result = "";
        var isReadText = text[0] != " " && text[0].charCodeAt(0) != 160;
        var i = 1;
        var start = 0;

        while (i < text.length) {
            if (isReadText) {
                while (i < text.length && text[i] != ' ' && text[i].charCodeAt(0) != 160) {
                    i++;
                }
                isReadText = false;
            }
            else {
                while (i < text.length && (text[i] == ' ' || text[i].charCodeAt(0) == 160)) {
                    i++;
                }

                isReadText = true;
            }
            var temp = text.substring(start, i);
            if (!isReadText) {
                result += "<span class='tooltip-word'>" + temp + "</span>";
            }
            else {
                result += "<span>" + temp + "</span>";
            }
            start = i;
            i++;
        }
    }

    return result;
}

function getTextNodesIn(node, includeWhitespaceNodes) {
    var textNodes = [];

    function getTextNodes(node) {
        if (node.nodeType == 3) {
            textNodes.push(node);
        } else {
            for (var i = 0, len = node.childNodes.length; i < len; ++i) {
                getTextNodes(node.childNodes[i]);
            }
        }
    }

    getTextNodes(node);
    return textNodes;
}

function getWindowWidth() {
    var width = 0;
    if (window.innerWidth) {
        width = window.innerWidth;
    }
    else if (document.documentElement && document.documentElement.clientWidth) {
        width = document.documentElement.clientWidth;
    }
    else if (document.body) {
        width = document.body.clientWidth;
    }
    return width;
}

function getWindowHeight() {
    var theHeight = 0;
    if (window.innerHeight) {
        theHeight = window.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientHeight) {
        theHeight = document.documentElement.clientHeight;
    }
    else if (document.body) {
        theHeight = document.body.clientHeight;
    }
    return theHeight;
}

function closeTooltip() {
    tooltipIsVisible = false;
    $('#tooltip').fadeOut();
    clearTimeout(timerTooltipID);
}

/*************************************************** TEST DATA **********************************************/
//this is an array of terms that has definition.
var arrTerms = ['Algorithm', 'Algorithm1', 'Algorithm2', 'Algorithm3', 'Algorithm4', 'Algorithm5', 'Algorithm6'];

//for example this is data in your DB
var arrDefinitionOfTerms = [
    { term: 'algorithm', definition: 'Definition:" an algorithm is basically an instance of logic written in software by software developers to be effective for the intended "target" computer(s), in order for the target machines to produce output from given input (perhaps null)".', url: 'http://en.wikipedia.org/wiki/Algorithm' },
    { term: 'algorithm1', definition: 'Definition:" an algorithm 1 is basically an instance of logic written in software by software developers to be effective for the intended "target" computer(s), in order for the target machines to produce output from given input (perhaps null)".', url: 'http://en.wikipedia.org/wiki/Algorithm' },
    { term: 'algorithm2', definition: 'Definition:" an algorithm 2 is basically an instance of logic written in software by software developers to be effective for the intended "target" computer(s), in order for the target machines to produce output from given input (perhaps null)".', url: 'http://en.wikipedia.org/wiki/Algorithm' },
    { term: 'algorithm3', definition: 'Definition:" an algorithm 3 is basically an instance of logic written in software by software developers to be effective for the intended "target" computer(s), in order for the target machines to produce output from given input (perhaps null)".', url: 'http://en.wikipedia.org/wiki/Algorithm' },
    { term: 'algorithm4', definition: 'Definition:" an algorithm 4 is basically an instance of logic written in software by software developers to be effective for the intended "target" computer(s), in order for the target machines to produce output from given input (perhaps null)".', url: 'http://en.wikipedia.org/wiki/Algorithm' },
    { term: 'algorithm5', definition: 'Definition:" an algorithm 5 is basically an instance of logic written in software by software developers to be effective for the intended "target" computer(s), in order for the target machines to produce output from given input (perhaps null)".', url: 'http://en.wikipedia.org/wiki/Algorithm' }
   ];
/*************************************************** TEST DATA **********************************************/